var ws = null;
function setConnected(connected) {
	document.getElementById('connect').disabled = connected;
	document.getElementById('disconnect').disabled = !connected;
	document.getElementById('echo').disabled = !connected;
}
function connect() {
	var target = document.getElementById('target').value;
	ws = new SockJS(target);
	//链接打开
	ws.onopen = function() {
		setConnected(true);
		log('链接打开!');
	};
	//当信息到来的时候
	ws.onmessage = function(event) {
		log('接收: ' + event.data);
	};
	//链接关闭的时候
	ws.onclose = function() {
		setConnected(false);
		log('链接关闭!');
	};
}

function disconnect() {
	if (ws != null) {
		ws.close();
		ws = null;
	}
	setConnected(false);
}

function echo() {
	if (ws != null) {
		var message = document.getElementById('message').value;
		log('发送: ' + message);
		ws.send(message);
	} else {
		alert('WebSocket链接断开,请先建立连接!');
	}
}
function log(message) {
	var console = document.getElementById('console');
	var p = document.createElement('p');
	p.style.wordWrap = 'break-word';
	p.appendChild(document.createTextNode(message));
	console.appendChild(p);
	while (console.childNodes.length > 25) {
		console.removeChild(console.firstChild);
	}
	console.scrollTop = console.scrollHeight;
}